package com.vogue.supplymall.account.shiro.filter;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.Gson;
import com.vogue.supplymall.common.domain.tool.MessageSourceUtils;

/**
 * shiro拦截过滤器基类
 * 
 * @author 崔岳
 *
 */
public abstract class BaseFilter extends AccessControlFilter {

	public static final Logger LOGGER_BASEFILTER = LoggerFactory.getLogger(BaseFilter.class);
	
	@Resource(name="messageSourceUtils")
	protected MessageSourceUtils messageSourceUtils;
	
	/**
	 * filter拦截返回错误信息<br>
	 * 
	 * @param request
	 * @param response
	 * @param errcode	系统错误号
	 */
	@SuppressWarnings("deprecation")
	public void ajaxResponse(ServletRequest request, ServletResponse response, int errcode,
			String...args) {
		String msg = null;
		if(messageSourceUtils == null) {
			System.out.println("Object is null");
		}else {
			msg = messageSourceUtils.getMessage(""+errcode, null);
			if(args != null) {
				msg = String.format(msg, args);
			}
		}
		HttpServletResponse httpResponse;
		HttpServletRequest httpRequest;
		Map<String, Object> map = new HashMap<String, Object>();
		httpResponse = WebUtils.toHttp(response);
		httpRequest = WebUtils.toHttp(request);
		WebUtils.saveRequest(request);
		if (httpRequest.getRequestURI() == null) {
			map.put("requestUri", "");
		} else {
			map.put("requestUri", httpRequest.getRequestURI());
		}
		if (httpRequest.getRequestURL() == null) {
			map.put("requestUrl", "");
		} else {
			map.put("requestUrl", httpRequest.getRequestURL());
			String url = httpRequest.getRequestURL().toString();
			url = url.substring(url.indexOf("/suppliermall"));
			System.out.println(url);
		}
		httpResponse.setStatus(404, "redirect");
		httpResponse.setCharacterEncoding("UTF-8");
//		httpResponse.setContentType("application/json; charset=utf-8");
		httpResponse.setContentType("text/plain; charset=utf-8");
//		httpResponse.setHeader("Access-Control-Allow-Origin", "http://192.168.11.104:8088,http://192.168.7.108:8080");
//		httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
		PrintWriter out = null;

		try {
			out = httpResponse.getWriter();
//			ErrorMsg ret = new ErrorMsg(errcode, msg);
//			JSONObject responseJSONObject = new JSONObject(ret);
//			out.append(responseJSONObject.toString());
			out.append("<h1>{\"code\":\""+errcode+"\",\"msg\":\""+msg+"\"}</h1>");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				out.close();
			}
		}
	}
	
	/**
	 * 根据参数名称获取请求中带过来的参数值
	 * @param request
	 * @param name
	 * @return
	 * @throws UnsupportedEncodingException
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	public Object getParameterByName(ServletRequest request, String name) throws UnsupportedEncodingException, IOException {
		Object value = request.getParameter(name);
		BufferedReader br = new BufferedReader(
				new InputStreamReader((ServletInputStream) request.getInputStream(), "utf-8"));		
		if (value == null) {			
			StringBuffer sb = new StringBuffer("");
			String temp;
			try {
				while ((temp = br.readLine()) != null) {
					sb.append(temp);
				}
			}catch(IOException ex){
			    LOGGER_BASEFILTER.error("Read Request JSON Stream ERROR :" + ex.getMessage());
			}finally {
				if(br != null) {
//					try {
//						br.close();
//						request.setAttribute(ConstantBean.REQUEST_STREAM_CLOSE_FLAG, true);
//					}catch(IOException ex) {
//						baselog.error("Close Read JSON Stream ERROR :" + ex.getMessage());
//					}
				}
			}
			String params = sb.toString();
			Gson json = new Gson();
			Map<String, Object> bean = json.fromJson(params, Map.class);
			if (bean != null) {
				if (StringUtils.isNotEmpty((String)bean.get(name))) {
					value = bean.get(name);
				} 
			}			
		}		
		return value;
	}
}
